package cn.yunyichina.provider.bone.service.impl;

import cn.yunyichina.provider.bone.dao.AdmissionsDao;
import cn.yunyichina.provider.bone.entity.Admissions;
import cn.yunyichina.provider.bone.utils.BeanValidator;
import cn.yunyichina.provider.bone.vo.AdmissionsAddInlandVo;
import cn.yunyichina.provider.bone.vo.AdmissionsAddVo;
import cn.yunyichina.provider.bone.vo.AdmissionsUpdateVo;
import cn.yunyichina.provider.bone.vo.AdmissionsVo;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.dubbo.service.OrderService;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.base.OrgApp;
import cn.yunyichina.provider.iface.entity.bone.OrderBoneExtendVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhuxp on 2018/2/7.
 *
 * @param
 * @Descrition 骨科高峰会报名
 */
@Service
@Log4j
public class AdmissionsServiceImpl {

    private static final String ORG_CODE = "rykj";
    private static final String ORG_ID = "ffdbc274acbd11e6990400163e0042e8";
    private static final String ORG_NAME = "广州仁医骨科科技有限公司";

    @Autowired
    private AdmissionsDao admissionsDao;

    /**
     * 报名记录列表
     * yyt.bone.admissions.list
     * @param data
     * @return
     */
    public Response listAdmissions(String data){
        log.info("查询报名记录入参："+data);
        Response response = new Response();
        try {
            AdmissionsVo admissionsVo = JsonUtils.parseObject(data,AdmissionsVo.class);
            if(admissionsVo.getIsVerify()==1){
                if(StringUtils.isBlank(admissionsVo.getVerificationCode())||StringUtils.isBlank(admissionsVo.getMobile())){
                    response.setResultCodeAndMessage(Response.FAILURE_CODE,"验证码或手机号不能为空!");
                    return response;
                }
                // 从缓存中获取验证码
                String verificationCode = CacheService.getGlobalKey("base", "verification_code", admissionsVo.getMobile());
                log.info("医生端验证码登录接口, 缓存中获取验证码为：" + verificationCode);
                // 验证验证码
                if (org.apache.commons.lang.StringUtils.isNotBlank(verificationCode) && verificationCode.trim().equalsIgnoreCase(admissionsVo.getVerificationCode().trim())) {
                    Admissions admissions =JsonUtils.parseObject(data,Admissions.class);
                    List<Admissions> admissionsList = admissionsDao.select(admissions);
                    //订单未支付 实时修改订单金额
                    /*国内订单 实时修改未支付订单金额*/
                    if(admissions.getRegionType()==1){
                        admissionsList= updatePayAmount(admissionsList);
                    }
                    response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE,Response.SUCCESS_MESSAGE,JsonUtils.toJsonString(admissionsList));
                    log.info("查询报名记录出参："+JsonUtils.toJsonString(admissionsList));
                }else {
                    response.setResultCodeAndMessage("1002", "验证码有误！");
                }
            }else if(admissionsVo.getIsVerify()==0){
                Admissions admissions =JsonUtils.parseObject(data,Admissions.class);
                List<Admissions> admissionsList=null;
                if(admissionsVo.getPageNum()!=null&&admissionsVo.getPageSize()!=null){
                    Map<String, Object> result = new HashMap<>();
                    //分页参数 为后台查询
                    long count = admissionsDao.selectCount(admissions);
                    PageInfo pageInfo = new PageInfo();
                    pageInfo.setPageNum(admissionsVo.getPageNum());
                    pageInfo.setPageSize(admissionsVo.getPageSize());
                    pageInfo.setTotal(count);
                    pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
                    admissionsList = admissionsDao.select(admissions,pageInfo);
                    /*国内订单 实时修改未支付订单金额*/
                    if(admissions.getRegionType()==1){
                       admissionsList= updatePayAmount(admissionsList);
                    }
                    result.put("list",admissionsList);
                    result.put("pageInfo",pageInfo);
                    response.setResult(JsonUtils.toJsonString(result));
                }else {
                    admissionsList = admissionsDao.select(admissions);
                    /*国内订单 实时修改未支付订单金额*/
                    if(admissions.getRegionType()==1){
                        admissionsList= updatePayAmount(admissionsList);
                    }
                    response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE,Response.SUCCESS_MESSAGE,JsonUtils.toJsonString(admissionsList));
                }
                log.info("查询报名记录出参："+JsonUtils.toJsonString(admissionsList));
            }else {
                response.setResultCodeAndMessage(Response.FAILURE_CODE,"参数isVerify不能为空！");
            }
        }catch (Exception e){
            log.error("查询报名记录异常!"+e);
            e.printStackTrace();
            response.setResultCodeAndMessage(Response.FAILURE_CODE,"查询报名记录异常！");
        }
        return  response;
    }


    /**
     * 报名内地
     * yyt.admissions.inland.insert
     * @param data
     * @return
     */
    public Response insertAdmissionsInland(String data){
        log.info("新增报名记录入参："+data);
        Response response = new Response();
        try {
            AdmissionsAddInlandVo admissionsAddVo = JsonUtils.parseObject(data,AdmissionsAddInlandVo.class);
            BeanValidator.validate(admissionsAddVo);
            /*/从缓存中获取验证码*/
            String verificationCode = CacheService.getGlobalKey("base", "verification_code", admissionsAddVo.getMobile());
            log.info("医生端验证码登录接口, 缓存中获取验证码为：" + verificationCode);
            // 验证验证码
            if (StringUtils.isBlank(verificationCode) || !verificationCode.trim().equalsIgnoreCase(admissionsAddVo.getVerificationCode().trim())) {
                response.setResultCodeAndMessage("1002", "验证码有误！");
                return response;
            }
            /* 验证手机号是否已经注册*/
            boolean flag = validatePhone(admissionsAddVo.getMobile());
            if(!flag){
                response.setResultCodeAndMessage(Response.FAILURE_CODE,"该手机号已提交报名信息，请在报名结果查询入口查询报名状态。");
                return response;
            }
            /*电子发票验证邮箱不能为空以及唯一性*/
            if(admissionsAddVo.getIsInvoice()==1){
                if(admissionsAddVo.getInvoiceType()==1){
                    if(admissionsAddVo.getEmail()==null){
                        response.setResultCodeAndMessage(Response.FAILURE_CODE,"邮箱不能为空!");
                        return response;
                    }
                    /* 验证邮箱是否已经注册*/
                    boolean flagEmail = validateEmail(admissionsAddVo.getEmail());
                    if(!flagEmail){
                        response.setResultCodeAndMessage(Response.FAILURE_CODE,"邮箱已注册!");
                        return response;
                    }
                }else if(admissionsAddVo.getMailingAddress()==null){
                    response.setResultCodeAndMessage(Response.FAILURE_CODE,"邮寄地址不能为空!");
                    return response;
                }
            }

            Admissions admissions = new Admissions();
            BeanUtils.copyProperties(admissionsAddVo,admissions);
            admissions.setId(PKGenerator.generateId());
            admissions.setCreatedTime(DateUtils.dateToString(new Date()));
            admissions.setUpdateTime(DateUtils.dateToString(new Date()));

            //获得platform
            OrgApp orgApp = null;
            Map<String, String> map = new HashMap<>();
            map.put("org_app_code",admissions.getPlatformOrgAppCode());
            log.info("根据org_app_code查询orgApp入参："+map);
            response = BaseService.callHumpFromInternal("yyt.base.orgapp.get" , JsonUtils.toJsonString(map));
            log.info("根据org_app_code查询orgAppc出参："+response);
            if("0".equals(response.getResultCode())){
                orgApp = JsonUtils.parseObject(response.getResult(), OrgApp.class);
            }else{
                response.setResultCodeAndMessage(Response.FAILURE_CODE , "ORG_APP_CODE error!");
                return response;
            }
            admissions.setPlatformId(orgApp.getOrgId());
            admissions.setPlatformName(orgApp.getOrgName());
            admissions.setPlatformCode(orgApp.getOrgCode());
            admissions.setPlatformOrgAppName(orgApp.getOrgAppName());
            admissions.setPlatformOrgAppCode(admissions.getPlatformOrgAppCode());
            admissions.setOrgCode(ORG_CODE);
            admissions.setOrgId(ORG_ID);
            admissions.setOrgName(ORG_NAME);

            String orderNo = CacheService.generateOrderNum(9, 6);
            admissions.setOrderNo(orderNo);
            admissions.setOrderStatus((short) 1);
            admissions.setPayStatus((short) 1); //未支付
            admissions.setPayAmount(queryPayAmount(admissions));
            admissions.setDataSource("2"); //来源微信端
            admissions.setRegionType((short) 1);

            //创建订单
            OrderExtVo orderVo = new OrderExtVo();
            BeanUtils.copyProperties(admissions,orderVo);
            orderVo.setId(PKGenerator.generateId());
            orderVo.setUserMobile(admissions.getMobile());
            orderVo.setUserAddress(admissions.getAddress());
            orderVo.setUserName(admissions.getFullName());
            orderVo.setUserSex(admissions.getSex());
            orderVo.setOrderType((short) 9); //骨科大会报名 订单类型：9

            //创建扩展订单
            OrderBoneExtendVo obeVo = new OrderBoneExtendVo();
            obeVo.setOrderNo(orderNo);
            obeVo.setId(PKGenerator.generateId());

            log.info("添加报名订单, 调用base模块, 添加订单入参request=" + JsonUtils.toJsonString(orderVo));
             Response baseRespone = BaseService.callUnderlineFromInternal("yyt.base.order.add",
                    JsonUtils.toJsonString(orderVo));
            log.info("添加报名订单, 调用base模块, 添加订单返回response=" + JsonUtils.toJsonString(baseRespone));
            if (!baseRespone.getResultCode().equals("0")) {
                response.setResultCodeAndMessage("1001", "生成订单失败!");
                return response;
            }

            log.info("添加报名订单, 调用order模块, 添加骨科订单拓展信息入参request=" + JsonUtils.toJsonString(obeVo));
            Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.extend.add",
                    JsonUtils.toJsonString(obeVo));
            log.info("添加报名订单, 调用order模块, 添加骨科订单拓展信息返回response=" + JsonUtils.toJsonString(orderRespone));
            if (!orderRespone.getResultCode().equals("0")) {
                response.setResultCodeAndMessage("1001", "生成订单失败！");
                return response;
            }

            //订单创建成功  新增报名记录
            admissionsDao.insert(admissions);
            response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE,Response.SUCCESS_MESSAGE,JsonUtils.toJsonString(admissions));
        }catch (Exception e){
            log.error("新增报名记录异常!"+e);
            e.printStackTrace();
            response.setResultCodeAndMessage(Response.FAILURE_CODE,"新增报名记录异常："+e);
        }
        return  response;
    }

    /**
     * 报名国外
     * yyt.bone.admissions.foreign.insert
     * @param data
     * @return
     */
    public Response insertAdmissionsForeign(String data){
        log.info("新增报名记录入参："+data);
        Response response = new Response();
        try {
            AdmissionsAddVo admissionsAddVo = JsonUtils.parseObject(data,AdmissionsAddVo.class);

             /* 验证手机号是否已经注册*/
            boolean flag = validatePhone(admissionsAddVo.getMobile());
            if(!flag){
                response.setResultCodeAndMessage(Response.FAILURE_CODE,"该手机号已提交报名信息，请在报名结果查询入口查询报名状态。");
                return response;
            }
            /* 验证邮箱是否已经注册*/
            boolean flagEmail = validateEmail(admissionsAddVo.getEmail());
            if(!flagEmail){
                response.setResultCodeAndMessage(Response.FAILURE_CODE,"邮箱已注册!");
                return response;
            }

            Admissions admissions = new Admissions();
            BeanUtils.copyProperties(admissionsAddVo,admissions);
            admissions.setId(PKGenerator.generateId());
            admissions.setCreatedTime(DateUtils.dateToString(new Date()));
            admissions.setUpdateTime(DateUtils.dateToString(new Date()));

            /*/获得platform
            OrgApp orgApp = null;
            Map<String, String> map = new HashMap<>();
            map.put("org_app_code",admissions.getPlatformOrgAppCode());
            response = BaseService.callHumpFromInternal("yyt.base.orgapp.get" , JsonUtils.toJsonString(map));
            if("0".equals(response.getResultCode())){
                orgApp = JsonUtils.parseObject(response.getResult(), OrgApp.class);
            }else{
                response.setResultCodeAndMessage(Response.FAILURE_CODE , "ORG_APP_CODE error!");
                return response;
            }
            admissions.setPlatformId(orgApp.getOrgId());
            admissions.setPlatformName(orgApp.getOrgName());
            admissions.setPlatformCode(orgApp.getOrgCode());
            admissions.setPlatformOrgAppName(orgApp.getOrgAppName());
            admissions.setPlatformOrgAppCode(admissions.getPlatformOrgAppCode());
            */
            admissions.setOrgCode(ORG_CODE);
            admissions.setOrgId(ORG_ID);
            admissions.setOrgName(ORG_NAME);

            String orderNo = CacheService.generateOrderNum(9, 6);
            admissions.setOrderNo(orderNo);
            admissions.setOrderStatus((short) 1);
            admissions.setPayStatus((short) 1); //未支付
            admissions.setDataSource("1"); //来源微信端
            admissions.setRegionType((short) 2);
            // 新增报名记录
            admissionsDao.insert(admissions);
            response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE,Response.SUCCESS_MESSAGE,JsonUtils.toJsonString(admissions));
        }catch (Exception e){
            log.error("新增报名记录异常!"+e);
            e.printStackTrace();
            response.setResultCodeAndMessage(Response.FAILURE_CODE,"新增报名记录异常！");
        }
        return  response;
    }

    /**
     * 更新记录--确认转账
     * yyt.bone.admissions.update
     * @param data
     * @return
     */
    public Response updateAdmissions(String data){
        log.info("更新报名记录入参："+data);
        Response response = new Response();
        try{
            AdmissionsUpdateVo updateVo = JsonUtils.parseObject(data,AdmissionsUpdateVo.class);
            Admissions admissions = admissionsDao.selectById(updateVo.getId());
            if(admissions==null){
                response.setResultCodeAndMessage(Response.FAILURE_CODE,"记录Id有误！");
                return  response;
            }
            admissions.setPayAmount(updateVo.getPayAmount());
            admissions.setPaymentDealId(updateVo.getPaymentDealId());
            admissions.setPayStatus((short) 3);
            admissions.setOrderStatus((short) 2);
            admissions.setPayTime(DateUtils.getDateTimeStr());
            admissions.setUpdateTime(DateUtils.getDateTimeStr());
            admissionsDao.update(admissions);
            response.setResultCodeAndMessage(Response.SUCCESS_CODE,Response.SUCCESS_MESSAGE);
        }catch (Exception e){
            log.error("更新报名记录异常!"+e);
            response.setResultCodeAndMessage(Response.FAILURE_CODE,"更新记录异常!");
        }
        return  response;
    }

    /**
     * 根据id查询单条记录
     * yyt.bone.admissions.query
     * @param data
     * @return
     */
    public Response queryAdmissions(String data){
        log.info("查询报名记录入参："+data);
        Response response = new Response();
        try {
            Admissions admissions = JsonUtils.parseObject(data,Admissions.class);
            if(StringUtils.isBlank(admissions.getId())){
                response.setResultCodeAndMessage(Response.FAILURE_CODE,"id不能为空！");
                return response;
            }
            Admissions resultAdmissions = admissionsDao.selectById(admissions.getId());
            log.info("查询报名记录出参："+JsonUtils.toJsonString(resultAdmissions));
            response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE,Response.SUCCESS_MESSAGE,JsonUtils.toJsonString(resultAdmissions));
        }catch (Exception e){
            log.info("查询报名记录异常"+e);
            e.printStackTrace();
            response.setResultCodeAndMessage(Response.FAILURE_CODE,"查询报名记录异常!");
        }
        return  response;
    }

    /**
     * 根据当前时间 获取订单金额
     * @return
     */
    private Integer queryPayAmount(Admissions admissions) throws ParseException {
        Integer payAmount = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long nowDate = System.currentTimeMillis();
        long dateOne = simpleDateFormat.parse("2018-05-30 00:00:00").getTime();
        long datTwo = simpleDateFormat.parse("2018-07-31 23:59:59").getTime();
        /* 身份类型：1：医生 2：学生&&护士 3:企业代表*/
        if(admissions.getIdentityType()==1){
            if(nowDate<dateOne){
                payAmount = 80000;
            }else if(dateOne<nowDate && nowDate<datTwo){
                payAmount = 100000;
            }else{
                payAmount=120000;
            }
        }else if(admissions.getIdentityType()==2){
            if(nowDate<dateOne){
                payAmount = 72000;
            }else if(dateOne<nowDate && nowDate<datTwo){
                payAmount = 90000;
            }else{
                payAmount=108000;
            }
        }else if(admissions.getIdentityType()==3){
            payAmount=100000;
        }
        return  payAmount;
    }

    private boolean validatePhone(String mobile){
        boolean flag =true;
        Admissions admissions = new Admissions();
        admissions.setMobile(mobile);
        List<Admissions> list = admissionsDao.select(admissions);
        if(!list.isEmpty()){
            flag =false;
        }
        return  flag;
    }

    private boolean validateEmail(String email) {
        boolean flag =true;
        Admissions admissions = new Admissions();
        admissions.setEmail(email);
        List<Admissions> list = admissionsDao.select(admissions);
        if(!list.isEmpty()){
            flag =false;
        }
        return  flag;
    }


    /**
     * 更新订单金额
     * @param admissionsList
     */
    private List<Admissions> updatePayAmount(List<Admissions> admissionsList) throws Exception {
        for(Admissions entity:admissionsList) {
            if (entity.getPayStatus() == 1) {
                Integer nowPayAmount = queryPayAmount(entity);
                if (nowPayAmount != entity.getPayAmount()) {
                    //金额已过期  修改订单与报名记录金额
                    Map<String, Object> jsonMap = new HashMap<>();
                    jsonMap.put("order_no", entity.getOrderNo());
                    log.info("获取订单信息, 调用order模块, 入参request=" + JsonUtils.toJsonString(jsonMap));
                    Response order = BaseService.callUnderlineFromInternal("yyt.base.order.by.orderno.get",
                            JsonUtils.toJsonString(jsonMap));
                    log.info("获取订单信息, 调用order模块, 返回respone=" + JsonUtils.toJsonString(order));
                    if (!order.getResultCode().equals("0")) {
                        throw new Exception("查询订单异常!");
                    }
                    OrderExtVo orderVo = JsonUtils.parseObject(order.getResult(), OrderExtVo.class);
                    orderVo.setPayAmount(nowPayAmount);
                    log.info("更新报名订单, 调用base模块, 更新订单入参request=" + JsonUtils.toJsonString(orderVo));
                    Response baseRespone = BaseService.callUnderlineFromInternal("yyt.base.order.update",
                            JsonUtils.toJsonString(orderVo));
                    log.info("更细报名订单, 调用base模块, 更新订单返回response=" + JsonUtils.toJsonString(baseRespone));
                    if (!baseRespone.getResultCode().equals("0")) {
                        throw new Exception("更新订单异常!");
                    }
                    entity.setPayAmount(nowPayAmount);
                    admissionsDao.update(entity);
                }
            }
        }
        return admissionsList;
    }

}
